# -*- coding: utf-8 -*-

import zmail
from queue import Queue, Empty
import time
from threading import Thread, Lock
import logging
import datetime
from functools import wraps


def singleton(cls):
    instances = {}

    @wraps(cls)
    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return get_instance


_logger = logging.getLogger(__name__)


@singleton
class Mail(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.queue = Queue()
        self.lock = Lock()

        self.super_mail = '87558708@qq.com'
        self.super_password = 'zdvncxdtnomfcade'

    def lockedstart(self):
        with self.lock:
            if not self.isAlive():
                self.daemon = True
                self.start()

    def send(self, email, subject, content_text):
        self.lockedstart()
        self.queue.put(('send', (email, subject, content_text)))

    def _send_mail(self, email, subject, content_text):
        mail = {'subject': subject, 'content_text': content_text}

        server = zmail.server(self.super_mail, self.super_password)
        if server.smtp_able():
            # SMTP function.
            try:
                server.send_mail([email], mail)
                _logger.info('send a mail to %s, %s; %s',
                             email, subject, content_text)

            except Exception as e:
                _logger.info('send mail to %s, error: %s.', e, email)

    def _rcv_mail(self):
        server = zmail.server(self.super_mail, self.super_password)
        if server.pop_able():
            pass
            # POP function.

    def run(self):
        while True:
            command, args = self.queue.get(True)
            if command == 'send':
                self._send_mail(*args)


mail_handler = Mail()
mail_handler.send('winboy99@163.com', 'odoo start', ' odoo start ok')

if __name__ == '__main__':
    mail_handler.send('winboy99@163.com', '通过程序发送邮件 测试!',
                      '这封邮件是用程序给你发过去的, 你能看到他, 就是程序 ok 了')

    time.sleep(10000)
